'use strict'

const jwt = require('../middlewares/jwt')
const userService = require('../services').userService

/**
 * 登录
 * @param {*} ctx 
 * @param {*} next 
 * @returns 
 */
const login = async (ctx, next) => {
  const { userName, password } = ctx.request.body
  if (!userName || !password) {
    console.log('用户名或密码不能为空')
  }

  const user = await userService.login(
    userName,
    password
  )
  if (user?.dataValues) {
    ctx.result = jwt.signToken(user?.dataValues)
  }
  return next()
}

/**
 * 获取用户详情
 * @param {*} ctx 
 * @param {*} next 
 * @returns 
 */
const getUserInfo = async (ctx, next) => {
  if (ctx.jwtData) {
    // 此处根据解密后的jwtData去获取用户详情
    const user = await userService.getUserInfo(ctx.jwtData.data.
      userId)
    const { userId, userName, status, role } = user.dataValues
    ctx.result = {
      userId, userName, status, role
    }
  }
  return next()
}
/**
 * 获取用户列表
 * @param {*} ctx 
 * @param {*} next 
 * @returns 
 */
const getUserList = async (ctx, next) => {
  if (ctx.jwtData) {
    // 此处根据解密后的jwtData去获取用户详情
    const userList = await userService.getUserList()
    ctx.result = userList
  }
  return next()
}
module.exports = {
  login,
  getUserInfo,
  getUserList
}
